package com.lfx.concurrent;

import java.util.Random;
import java.util.concurrent.Exchanger;

/**
 * @author 李逢喜
 * create 2021/8/3
 */
public class ExchangeMain {


    public static void main(String[] args) {
        Exchanger<String> exchanger=new Exchanger<>();
        Random random=new Random();
        new Thread("线程1"){
            @Override
            public void run() {
                while (true){
                    try {
                        String otherData=exchanger.exchange("交换数据1");
                        System.out.println(Thread.currentThread().getName()+ "得到<==" + otherData);
                        Thread.sleep(random.nextInt(2000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();

        new Thread("线程2"){
            @Override
            public void run() {
                while (true){
                    try {
                        String otherData=exchanger.exchange("交换数据2");
                        System.out.println(Thread.currentThread().getName()+ "得到<==" + otherData);
                        Thread.sleep(random.nextInt(2000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();

        new Thread("线程3"){
            @Override
             public void run() {
                while (true){
                    try {
                        String otherData=exchanger.exchange("交换数据3");
                        System.out.println(Thread.currentThread().getName()+ "得到<==" + otherData);
                        Thread.sleep(random.nextInt(2000));

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();

    }
}
